import re

from lab.common.auth import LoginRequired, RefreshTokenRequired
from lab.common.base_model_view_set import BaseModelViewSet
from lab.common.enums import ErrorCodeEnum
from lab.common.response import OK, AuthenticationFailed
from lab.user.models import ExtendedUser, TokenBlacklist
from lab.user.serializers import ExtendedUserSerializer
from lab.utils.jwt_utils import JwtUtils


class LoginViewSet(BaseModelViewSet):
    """方便测试，获取用户id为1用户的token"""

    def retrieve(self, request):
        extended_user = ExtendedUser.objects.get(id=30)
        return OK({
            'user_id': extended_user.id,
            'user_name': extended_user.user.username,
            'token': JwtUtils.generate_jwt_token(extended_user.id, extended_user.user.username),
            'refresh_token': JwtUtils.generate_jwt_refresh_token(extended_user.id, extended_user.user.username)
        })


class UserViewSet(BaseModelViewSet):
    """
    retrieve:
        获取用户个人信息
    update:
        更新用户信息，body里除了例子里还有两个字段：email/user_name，swagger这个地方有点问题

    """
    authentication_classes = (LoginRequired,)
    serializer_class = ExtendedUserSerializer

    def get_object(self):
        return self.request.user


class UserSearchViewSet(BaseModelViewSet):
    """
    retrieve:
        模糊查询用户信息
    """

    def retrieve(self, request, *args, **kwargs):
        keyword = kwargs.get('keyword')
        user_list = ExtendedUser.objects.filter(user__username__icontains=keyword).filter(user__is_active=1).all()
        return OK(ExtendedUserSerializer(user_list, many=True).data)


class LogoutViewSet(BaseModelViewSet):
    """
    retrieve:
        注销登录
    """
    authentication_class = (LoginRequired,)

    def retrieve(self, request, *args, **kwargs):
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            raise AuthenticationFailed(ErrorCodeEnum.INVALID_TOKEN.value)
        token = re.match(r'[bB]earer\s(\w+\.\w+\..+)', token).group(1)
        TokenBlacklist.objects.create(token=token)
        return OK('Logout successful')


class TokenRefreshViewSet(BaseModelViewSet):
    """
    retrieve:
        刷新token
    """
    authentication_classes = (RefreshTokenRequired,)

    def retrieve(self, request, *args, **kwargs):
        extended_user = request.user
        return OK({
            'user_id': extended_user.id,  # this is the extended user
            'user_name': extended_user.user.username,
            'token': JwtUtils.generate_jwt_token(extended_user.id, extended_user.user.username),
            'refresh_token': JwtUtils.generate_jwt_refresh_token(extended_user.id, extended_user.user.username)
        }, msg='Token已刷新')
